package com.heima.admin.controller.v1;

import com.heima.admin.entity.AdChannel;
import com.heima.admin.service.AdChannelService;
import com.heima.common.dtos.PageResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.admin.dtos.ChannelDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
public class AdChannelController {

    @Autowired
    private AdChannelService adChannelService;

    @PostMapping("/api/v1/channel/list")
    public PageResult<ChannelDto> fingByPage(@RequestBody ChannelDto dto) {

        return adChannelService.findByPage(dto);

    }

    @PostMapping("/api/v1/channel/save")
    public ResponseResult save(@RequestBody ChannelDto dto) {
        if(StringUtils.isBlank(dto.getName())){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID);
        }
        AdChannel adChannel = BeanHelper.copyProperties(dto, AdChannel.class);
        adChannel.setCreatedTime(new Date());
        adChannelService.save(adChannel);
        return ResponseResult.ok();
    }

    @PutMapping("/api/v1/channel/update")
    public ResponseResult update(@RequestBody ChannelDto dto) {

        adChannelService.updateda(dto);
        return ResponseResult.ok();
    }

    @DeleteMapping("/api/v1/channel/del/{id}")
    public ResponseResult deleteById(@PathVariable(name = "id") Integer id) {

        AdChannel byId = adChannelService.getById(id);
        if (byId != null && byId.getStatus() == 1) {
            throw new LeadException(AppHttpCodeEnum.DATA_CAN_NOT_DEL);
        }
        adChannelService.removeById(id);
        return ResponseResult.ok();
    }
@GetMapping("/api/v1/channel/channels")
    public ResponseResult<List<AdChannel>> channels(){
    return     ResponseResult.ok(adChannelService.list());
}

}
